import VideoPreview from '@/components/VideoPreview';
import useSyncState from '@/views/hooks/useSyncState';
import styled from '@emotion/styled';
import AgentServer, { IEvent } from '@/modules/Agent';
import { Button, Form, Select } from 'antd';

import { t } from 'i18next';
import React, { useEffect, useState } from 'react';

interface DeviceInfo {
	value: string;
	label: string;
}

interface VideoConfigureProps {
	mode: 'audio' | 'video' | 'speaker';
	selectKey: string;
	videoInput: MediaDeviceInfo[];
	defaultDevice: MediaDeviceInfo | undefined;
	onOk: () => void;
	onCancel: () => void;
	onSelect: (id: string | undefined) => void;
}

const Submit = styled.div`
	padding-top: 10px;
	text-align: right;
	.ant-btn-default {
		background-color: #fff;
	}
	.ant-btn-primary {
		margin-left: 8px;
	}
`;

const VideoConfigure = (props: VideoConfigureProps) => {
	const { videoInput = [], mode = 'video', selectKey = '1', onOk, onCancel, onSelect, defaultDevice } = props;
	const [form] = Form.useForm();

	const [videoDevice, setVideoDevice] = useState<DeviceInfo[]>([
		{
			value: 'default',
			label: t('default-device')
		}
	]);

	const [selectedID, setSelectedID] = useSyncState<string | undefined>('default');

	const [localStream, setLocaStream] = useSyncState<MediaStream | null>(null);

	const createLocalVideo = async (deviceId?: string) => {
		const constraints = {
			audio: false,
			video: {
				width: 480,
				height: 320,
				deviceId: deviceId
			}
		};
		try {
			const stream = await navigator.mediaDevices.getUserMedia(constraints);
			setLocaStream(stream);
			setSelectedID(deviceId);
			onSelect(deviceId);
		} catch (error) {
			console.log('create local stream failed', error);
		}
	};

	const stopLocal = () => {
		if (localStream()) {
			const traks = localStream()?.getTracks();
			traks?.map(track => track.stop());
		}
	};

	useEffect(() => {
		if (selectKey === '1') {
			createLocalVideo(defaultDevice?.deviceId);
		} else {
			stopLocal();
		}

		return () => {
			stopLocal();
		};
	}, [selectKey]);

	useEffect(() => {
		const list = videoInput.map(item => ({ value: item.deviceId, label: item.label }));
		setVideoDevice([
			{
				value: 'default',
				label: t('default-device')
			},
			...list
		]);
	}, [videoInput]);

	const selectCamera = (id: string) => {
		stopLocal();
		createLocalVideo(id);
	};

	const ok = () => {
		stopLocal();
		onOk();
	};

	const cancel = () => {
		stopLocal();
		onCancel();
	};

	useEffect(() => {
		form.setFieldValue('videoDeviceID', defaultDevice?.deviceId || 'default');
		setSelectedID(defaultDevice?.deviceId);
	}, [defaultDevice]);

	return (
		<>
			<Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} layout="horizontal" style={{ maxWidth: 700 }}>
				<Form.Item label={t('select-device')} name="videoDeviceID" labelAlign="left">
					<Select disabled={videoDevice.length === 1} defaultValue={defaultDevice?.deviceId || 'default'} onChange={selectCamera}>
						{videoDevice.map(item => (
							<Select.Option key={item.value} value={item.value}>
								{item.label}
							</Select.Option>
						))}
					</Select>
				</Form.Item>
				<VideoPreview width={480} height={320} stream={localStream()} />
			</Form>
			<Submit>
				<Button type="default" onClick={cancel}>
					{t('cancel')}
				</Button>
				<Button type="primary" onClick={ok}>
					{t('sure')}
				</Button>
			</Submit>
		</>
	);
};

export default VideoConfigure;
